package com.leetcode.algorithm.y22.m09.w4;

import java.util.Arrays;

/**
 * 1652. 拆炸弹
 * 
 * https://leetcode.cn/problems/defuse-the-bomb/
 * 
 * @author jie.deng
 *
 */
class Question1652Solution01 {

	public int[] decrypt(int[] code, int k) {
		int len = code.length;
		int[] result = new int[len];
		if (k == 0) {
			Arrays.fill(result, 0);
			return result;
		}

		int[] prefixSum = new int[len];
		prefixSum[0] = code[0];
		for (int i = 1; i < len; i++) {
			prefixSum[i] = code[i] + prefixSum[i - 1];
		}

		if (k > 0) {
			for (int i = 0; i < len; i++) {
				if (i + k >= len) {
					result[i] = prefixSum[len - 1] + prefixSum[i + k - len] - prefixSum[i];
				} else {
					result[i] = prefixSum[i + k] - prefixSum[i];
				}
			}
		} else {
			k = -k;
			for (int i = 0; i < len; i++) {
				if (i == 0) {
					result[i] = prefixSum[len - 1] - prefixSum[len - 1 - k];
				} else if (i > k) {
					result[i] = prefixSum[i - 1] - prefixSum[i - 1 - k];
				} else {
					result[i] = prefixSum[i - 1] + (prefixSum[len - 1] - prefixSum[len - 1 - (k - i)]);
				}
			}
		}

		return result;
	}

}